package com.test.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.test.dao.DomainDAO;
import com.test.pojo.Domain;
import com.test.service.DomainService;
import com.test.util.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author 徒有琴
 */

@Service
public class DomainServiceImpl implements DomainService {
    Logger log = LoggerFactory.getLogger(DomainServiceImpl.class);
    @Autowired
    private DomainDAO domainDAO;

    @Override
    public Result addDomain(Domain domain) {//添加
        //检查域名和端口是否已经映射
        Result res = check(domain.getAddr(), domain.getPort());
        if (res.isSuccess()) {//没有映射
            domainDAO.addDomain(domain);
            res.setSuccess(true);
        }
        return res;
    }

    @Override
    public Result checkAddrAndPort(String addr, Integer port) {
        Result res = check(addr, port);
        return res;
    }

    private Result check(String addr, Integer port) {
        Result res = new Result();
        List<Domain> list = domainDAO.getDomainByAddrAndPort(addr, port);
        //如果查不到结果的话，mybatis会返回一个长度为0的list
        if (list != null && list.size() > 0) {
            res.setSuccess(false);
            res.setMessage("域名和端口已经映射");
            res.setOther(list.get(0).getId());
        } else {
            res.setSuccess(true);
        }
        return res;
    }

    @Override
    public PageInfo<Domain> getDomainList(Domain domain, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Domain> list = domainDAO.getDomainList(domain);
        PageInfo pageInfo = new PageInfo(list);
        return pageInfo;
    }

    @Override
    public void deleteDomainById(Integer id) {
        domainDAO.deleteDomainById(id);
        log.info("删除域名：" + id);
    }

    //冗余
    @Override
    public Domain getDomainById(Integer id) {
        Domain domain = domainDAO.getDomainById(id);
        return domain;
    }

    @Override
    public Result updateDomain(Domain domain) {
        Result res = check(domain.getAddr(), domain.getPort());
        if (res.isSuccess() || domain.getId().equals(res.getOther())) {//不存在或存在的就是自己
            domainDAO.updateDomain(domain);
            res.setSuccess(true);
        }
        return res;
    }
}
